#!/bin/sh
#reads InstallDir from plist and creates symlink in tmp

#Find out where .app is installed to
PACKAGEDIR="${1}"
PRODUCTNAME=`defaults read "${PACKAGEDIR}/Contents/Info" "NIProductName"`
PLISTNAME=`defaults read "${PACKAGEDIR}/Contents/Info" "NIPlistName"`
APPFILENAME=`defaults read "${PACKAGEDIR}/Contents/Info" "NIAppFileName"`
PKGNAME=$(basename "$PACKAGEDIR" .pkg)

echo "Package Folder: ${PACKAGEDIR}"
echo "Product Name: ${PRODUCTNAME}"
echo "Plist Name: ${PLISTNAME}"
echo "PKG Name: ${PKGNAME}"

FAILED=FALSE
INSTALLDIR=$("${PACKAGEDIR}/Contents/Resources/pathhelper" read "/Library/Preferences/${PLISTNAME}" "InstallDir")

if [ ! -e "${INSTALLDIR}" ]; then
	if [[ $PKGNAME == *Controller* || $PKGNAME == *Service* ]]; then
		INSTALLDIR="/Applications/Native Instruments/${PRODUCTNAME}"
		echo "Install Folder: ${INSTALLDIR}"
		
		if [ ! -e "/Applications/Native Instruments" ]; then
			mkdir "/Applications/Native Instruments"
			chmod -R 775 "/Applications/Native Instruments"
		fi
		if [ ! -e "/Applications/Native Instruments/${PRODUCTNAME}" ]; then
			mkdir "/Applications/Native Instruments/${PRODUCTNAME}"
			chmod -R 775 "/Applications/Native Instruments/${PRODUCTNAME}"
		fi
	
		ln -s "${INSTALLDIR}" "/tmp/${PKGNAME}"
		
		if ! "${PACKAGEDIR}/Contents/Resources/pathhelper" writedir "/Library/Preferences/${PLISTNAME}" "InstallDir" "${INSTALLDIR}"; then
			echo "** FAILED pathhelper writedir **"
			FAILED=TRUE
		fi
	else
		echo "** FAILED pathhelper read - InstallDir could not be read or does not exist. **"
		FAILED=TRUE
	fi
else
	echo "Install Folder: ${INSTALLDIR}"
	
	if [[ $PKGNAME == *Application* ]]; then
		echo "Application File Name: ${APPFILENAME}"
		rm -rf "${INSTALLDIR}/${APPFILENAME}.app"
	fi

	ln -s "${INSTALLDIR}" "/tmp/${PKGNAME}"
	
	#exception for products that were released with old RAS version
	if [ "$PRODUCTNAME" = "B4 II" -o "$PRODUCTNAME" = "Reaktor 5" ]; then
		defaults write "/Library/Preferences/${PLISTNAME}" RASVersion -string "2"
	fi
fi

if [ $FAILED = TRUE ]; then
	echo "At least one failure occurred in script '${SCRIPT_NAME}' in package '${PACKAGEDIR}'."
	exit 1
fi

